/*
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/1/12 18:34
@File     : user_util.go
@Project  : gohub
@Desc     :
*/
package user

import (
	"github.com/gin-gonic/gin"
	"gohub/pkg/app"
	"gohub/pkg/database"
	"gohub/pkg/paginator"
)

// IsEmailExist 判断email是否已被注册
func IsEmailExist(email string) bool {
	var count int64
	database.DB.Model(User{}).Where("email=?", email).Count(&count)
	return count > 0
}

// IsPhoneExist 判断手机号是否已被注册
func IsPhoneExist(phone string) bool {
	var count int64
	database.DB.Model(User{}).Where("phone=?", phone).Count(&count)
	return count > 0
}

// GetByPhone 通过手机号获取用户
func GetByPhone(phone string) (userModel User) {
	database.DB.Where("phone = ?", phone).First(&userModel)
	return
}

// GetByMulti 通过 手机号/Email/用户名 来获取用户
func GetByMulti(LoginID string) (userModel User) {
	database.DB.Where("phone = ?", LoginID).Or("email = ?", LoginID).Or("name = ?", LoginID).First(&userModel)
	return
}

// All
// @Description: 获取所有用户数据
// @return users
func All() (users []User) {
	database.DB.Find(&users)
	return
}

/**
 * Get
 * @Description: 通过ID获取用户
 * @param id
 * @return userModel
 */
func Get(id string) (userModel User) {
	database.DB.Where("id", id).First(&userModel)
	return
}

/**
 * GetByEmail
 * @Description: 通过email获取用户
 * @param email
 * @return userModel
 */
func GetByEmail(email string) (userModel User) {
	database.DB.Where("email=?", email).First(&userModel)
	return
}

// Paginate
// @Description: 分页内容
// @param c
// @param perPage
// @return users
// @return paging
func Paginate(c *gin.Context, perPage int) (users []User, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(User{}),
		&users,
		app.V1URL(database.TableName(&User{})),
		perPage,
	)
	return
}
